package com.sense.kukoo.biz_me.view

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.sense.feel.common.global.bean.WebPage
import com.sense.feel.common.utils.ToastUtils
import com.sense.kukoo.biz_me.R
import com.sense.kukoo.biz_me.adapter.MeChannelAdapter
import com.sense.kukoo.biz_me.vm.MeViewModel
import com.sense.kukoo.common.constant.ARouterUrl
import com.sense.kukoo.biz_me.databinding.BizMeFragmentMeBinding
import com.sense.kukoo.common.constant.ConstantConfig
import com.sense.kukoo.common.event.LogoutEvent
import com.sense.kukoo.common.event.MainPageEvent
import com.sense.kukoo.common.event.UserEditEvent
import com.sense.kukoo.common.listener.OnScrollYChangedListener
import com.sense.kukoo.common.media.Kukoo
import com.sense.kukoo.common.media.bean.LocalMediaListItemBean
import com.sense.kukoo.common.media.watcher.UserWatcher
import com.sense.kukoo.common.mvvm.view.BaseMvvmFragment
import com.sense.kukoo.common.repo.http.bean.IndexContentBean
import com.sense.kukoo.common.repo.http.bean.UserInfoBean
import com.sense.kukoo.common.utils.ApplicationContext
import com.sense.kukoo.common.utils.ClipboardUtil
import com.sense.kukoo.common.wiget.state.NetworkErrorState
import com.zy.multistatepage.state.SuccessState
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MeFragment : BaseMvvmFragment<MeViewModel, BizMeFragmentMeBinding>() {

    private val TAG: String = javaClass.simpleName

    private lateinit var mAdapter: MeChannelAdapter

    var mCurrentMusic: LocalMediaListItemBean? = null
    var mCurrentPlayState: Int = UserWatcher.MusicStateWatcher.STATE_NOT_PLAYING

    private var mOnScrollYChangedListener:OnScrollYChangedListener? = null

    companion object {
        @JvmStatic
        fun newInstance() = MeFragment()
    }

    override fun getLayout(): Int = R.layout.biz_me_fragment_me

    override fun getViewModelClass(): Class<MeViewModel> = MeViewModel::class.java

    override fun initParam() {}

    override fun responseVM(action: Int) {}

    override fun initData() {
        mBinding.lifecycleOwner = this
        mBinding.vm = mViewModel
        //
        bindData(mViewModel.data_channelContent){
            mBinding.multiStateContainer.show<SuccessState>()
            mAdapter.list = it
            mAdapter.notifyDataSetChanged()
        }
        bindAction(mViewModel.action_network_error){
            mBinding.multiStateContainer.show<NetworkErrorState> {
                it.onRetry {
                    mViewModel.onNetworkRetry()
                }
            }
        }
        bindData(mViewModel.data_enableLoadMore){
            mBinding.refreshLayout.setEnableLoadMore(it)
        }
        bindAction(mViewModel.action_finishRefres){
            mBinding.refreshLayout.finishRefresh()
        }
        bindAction(mViewModel.action_finishLoadMore){
            mBinding.refreshLayout.finishLoadMore()
        }
        bindAction(mViewModel.action_toSettingsPage){
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_ME_MODULE_SETTINGS_ACTIVITY)
                .navigation()
        }
        bindAction(mViewModel.action_toCreatorPage){
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_LOGIN_MODULE_WEB_ACTIVITY)
                .withParcelable(ConstantConfig.ARG1, WebPage(url = ConstantConfig.URL.h5Cooperation()))
                .navigation()
        }
        bindAction(mViewModel.action_toCreatorUploadPage){
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_LOGIN_MODULE_WEB_ACTIVITY)
                .withParcelable(ConstantConfig.ARG1, WebPage(url = ConstantConfig.URL.h5CreatorUploadDescription()))
                .navigation()
        }
        bindAction(mViewModel.action_toMyHistoryPage){
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_HISTORY_ACTIVITY)
                .navigation()
        }
    }

    override fun initView() {
        mAdapter = MeChannelAdapter(mutableListOf(), mListener)
        mBinding.recyclerView.adapter = mAdapter

        val linearLayoutManager = LinearLayoutManager(context)
        mBinding.recyclerView.layoutManager = linearLayoutManager
        mBinding.refreshLayout.setOnRefreshListener {
            //OnRefresh
            mViewModel.onRefreshData()
        }
        mBinding.refreshLayout.setOnLoadMoreListener {
            //OnLoadMore
            mViewModel.onLoadMoreData()
        }
        //
        mBinding.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {

            private var isScroll = false

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                if (isScroll) {
                    mOnScrollYChangedListener?.onChanged(2, 0, dy, RecyclerView.SCROLL_STATE_DRAGGING)
                }
            }

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                if(newState == RecyclerView.SCROLL_STATE_IDLE){
                    isScroll = false
                    mOnScrollYChangedListener?.onChanged(2, 0, 0, RecyclerView.SCROLL_STATE_IDLE)
                } else {
                    isScroll = true
                }
            }
        })
    }

    override fun singleLazyLoad() {
        mBinding.refreshLayout.autoRefresh()
    }

    private val mListener = object : MeChannelAdapter.IndexContentEventListener {
        override fun onUserIconClick(user: UserInfoBean) {
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_ME_MODULE_PROFILE_ACTIVITY)
                .navigation()
        }

        override fun onUserChannelClick(user: UserInfoBean) {
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_ME_MODULE_PROFILE_ACTIVITY)
                .navigation()
        }

        override fun onUserIdClick(user: UserInfoBean) {
            val idStr = "${user.id}"
            if (ClipboardUtil.copy(idStr)) {
                ToastUtils.showToast(ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.hint_copy_success))
            }
        }

        override fun onItemClick(data: IndexContentBean) {
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_DESCRIPTION_ACTIVITY)
                .withString(ARouterUrl.KEY_FROM, "${data.id}")
                .navigation()
        }

        override fun onChannelClick(data: IndexContentBean) {
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_CHANNEL_ACTIVITY)
                .withString(ARouterUrl.KEY_FROM, "${data.userId}")
                .navigation()
        }

        override fun onBtnPlayClick(data: IndexContentBean) {
            if(mCurrentMusic?.idOfChapter() == data.id){
                //当前的
                when (mCurrentPlayState) {
                    UserWatcher.MusicStateWatcher.STATE_ERROR_RETRYING,
                    UserWatcher.MusicStateWatcher.STATE_SEEKING,
                    UserWatcher.MusicStateWatcher.STATE_PREPARE,
                    UserWatcher.MusicStateWatcher.STATE_PLAYING -> {
                        Kukoo.input.pause()
                    }
                    /*UserWatcher.MusicStateWatcher.STATE_NOT_PLAYING ->{}
                    UserWatcher.MusicStateWatcher.STATE_PAUSE ->{}*/
                    else -> {
                        Kukoo.input.start()
                    }
                }
            }else{
                //非当前的
                Kukoo.input.play(LocalMediaListItemBean(data))
            }
        }

        override fun onBtnFollowersClick(user: UserInfoBean) {
            if(user.fansNum > 0){
                ARouter.getInstance()
                    .build(ARouterUrl.ROUTE_ME_MODULE_FOLLOWINGS_LIST_ACTIVITY)
                    .withString(ARouterUrl.KEY_FROM, "1")
                    .navigation()
            }
        }

        override fun onBtnFollowingsClick(user: UserInfoBean) {
            if(user.subscriptionNum > 0){
                ARouter.getInstance()
                    .build(ARouterUrl.ROUTE_ME_MODULE_FOLLOWINGS_LIST_ACTIVITY)
                    .withString(ARouterUrl.KEY_FROM, "0")
                    .navigation()
            }
        }

    }

    fun setOnScrollYChangedListener(l: OnScrollYChangedListener){
        mOnScrollYChangedListener = l
    }

    private val mWatcher = object: UserWatcher.MusicStateWatcher{

        override fun onMusicChanged(music: LocalMediaListItemBean) {
            mCurrentMusic = music
            mAdapter.setCurrentMusic(music)
        }

        override fun onPlayTimeChanged(currentInt: Int, totalInt: Int, current: String, total: String) {}

        override fun onPlayPercentChanged(percent: Int) {}

        override fun onPlayStateChanged(state: Int) {
            mCurrentPlayState = state
            mAdapter.setCurrentPlayState(state)
        }

        override fun onPlaySpeedChanged(speed: Float) {}

        override fun onPlayListChanged() {}
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: LogoutEvent) {
        mViewModel.onLogout()
        //退出me页面
        EventBus.getDefault().post(MainPageEvent(0))
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: UserEditEvent) {
        /*initLoginState()*/
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        EventBus.getDefault().register(this)
        Kukoo.watcher.register(mWatcher)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        Kukoo.watcher.unregister(mWatcher)
    }

}